/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
	ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2)
	{
		ListNode* cur1 = pHead1;
		ListNode* cur2 = pHead2;
		int n1 = 0, n2 = 0;
		while (cur1)
		{
			cur1 = cur1->next;
			n1++;
		}
		while (cur2)
		{
			cur2 = cur2->next;
			n2++;
		}
		int k = abs(n1 - n2);
		if (n1 > n2)
		{
			ListNode* fast = pHead1;
			ListNode* slow = pHead2;
			while (k--)
			{
				fast = fast->next;
			}
			while (slow != fast)
			{
				slow = slow->next;
				fast = fast->next;
			}
			if (slow == fast) return slow;
			else return nullptr;
		}
		else
		{
			ListNode* fast = pHead2;
			ListNode* slow = pHead1;
			while (k--)
			{
				fast = fast->next;
			}
			while (slow != fast)
			{
				slow = slow->next;
				fast = fast->next;
			}
			if (slow == fast) return slow;
			else return nullptr;
		}
		return nullptr;

	}
};
